<?php
/**
 * M1我的跟单
 */

namespace app\admin\model;

use think\Db;
use app\v2\model\Order;
use app\v2\model\Apply;

class Documentary extends Common
{
    protected $name = 'apply';
    /**
     * 我的跟单数据
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-08T14:40:23+0800
     * @param    integer $uid 当前管理员id
     * @param    string $keywords 关键字
     * @param    integer $page 页码
     * @param    integer $limit 每页数量
     * @return   array
     */
    public function getDataList($uid, $keywords, $page = 1, $limit = 15, $valuedate, $startdate, $enddate, $os = '', $status = "")
    {
        $order = 'status = 2 desc,auth_type desc,status = 9 desc,auth_type desc,status = 3 desc,auth_type desc,status asc,auth_type desc,third_claim_date desc,auth_type desc,id desc,auth_type desc';
        if ($keywords == '全部跟单') {
            $keywords = '';
            $map = array();
            if ($valuedate) {
                $valuedate = substr($valuedate, 0, 10);
                $valuedate = date('Y-m-d', strtotime("$valuedate +1 day"));
                $map['time'] = ['like', '%' . $valuedate . '%'];
            }
            if ($os) {
                $map['os'] = $os;
            }

            if ($uid != 1) {
                $map['merchandiser'] = $uid;
            } else {
                $map['status'] = array('in', '2,3,4,5,9,10,11,12');
            }

            if (in_array($status, [2, 3, 4, 5, 9, 10, 11, 12])) {
                $map2['status'] = $status;
            }

            $map['transfer'] = 0;

            //回收显示未发货状态
            $map['huishou_status'] = ['eq','0'];

            $dataCount = $this->where($map)->where($map2)->count();
            $list = $this
                ->where($map)
                ->where($map2)
                ->order($order)
                ->page($page, $limit)
                ->select();
            $list = modelo2array($list);
            foreach ($list as $key => $value) {
                $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);  //逾期处理
                $list[$key]['info'] = $this->statusInfo($list[$key]['status']);          //状态信息

                $list[$key]['already_money'] = self::alreadyRepay($value, $list[$key]['status']);//已还总金额
                $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
                $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

                $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
                $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
                $list[$key]['user_admin3'] = $this->getNameById($value['treasurer']);      //财务员
                $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);   //跟单员M1
                $list[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

                $list[$key]['delay_transfer_date'] = $this->transferTime($value);  //延时移交时间

//                $delayMoney = model('v2/Apply')->delayMoney($value);
//                $list[$key]['this_delay_money'] = $delayMoney['money_order'];  //本次延期总费
                $list[$key]['this_delay_money'] = $this->getDelayMoney($value);

                //是否留案
                $list[$key]['is_liuan'] = $this->isLiuan($value);

                $mapseq['apply_id'] = $value['id'];
                $mapseq['auth_admin'] = 2;
                $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
                if (!$dataseq) {
                    $list[$key]['seq'] = '';
                } else {
                    $list[$key]['seq'] = $dataseq['seq'];
                }
            }

            $data['list'] = $list;
            $data['dataCount'] = $dataCount;
            //财务改动 线上线下配置
            $data['pay_model'] = config('PAY_MODE');
            return $data;
        }

        // 今日到期
        if ($keywords == '今日到期') {

            $time = date('Y-m-d', time());
            $keywords = $time;
            $map = array();
            if ($keywords) {
                $map['appoint_time'] = ['like', '%' . $keywords . '%'];
            }
//            if($os)
//            {
//                $map['os'] = $os;
//            }
            if ($uid != 1) {
                $map['merchandiser'] = $uid;
                $map['status'] = array('in', '3,12');
            } else {
                $map['status'] = array('in', '3,12');

            }

            //回收显示未发货状态
            $map['huishou_status'] = ['eq','0'];

            $map['transfer'] = 0;
            $dataCount = $this->where($map)->where($map2)->count();
            $list = $this
                ->where($map)
                ->where($map2)
                ->order('status asc,third_claim_date desc,id desc')
                ->page($page, $limit)
                ->select();
            $list = modelo2array($list);
            foreach ($list as $key => $value) {
                $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);  //逾期处理
                $list[$key]['info'] = $this->statusInfo($list[$key]['status']);          //状态信息
                $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
                $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
                $list[$key]['user_admin3'] = $this->getNameById($value['treasurer']);      //财务员
                $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);   //跟单员M1
                $list[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

                $list[$key]['already_money'] = self::alreadyRepay($value, $list[$key]['status']);//已还总金额
                $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
                $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

//                $delayMoney = model('v2/Apply')->delayMoney($value);
//                $list[$key]['this_delay_money'] = $delayMoney['money_order'];  //本次延期总费
                $list[$key]['this_delay_money'] = $this->getDelayMoney($value);
            }

            $data['list'] = $list;
            $data['dataCount'] = $dataCount;
            //财务改动 线上线下配置
            $data['pay_model'] = config('PAY_MODE');
            return $data;
        }


        // 明日到期
        if ($keywords == '明日到期') {

            $time = date('Y-m-d', strtotime("+1 day"));
            $keywords = $time;
            $map = array();
            if ($keywords) {
                $map['appoint_time'] = ['like', '%' . $keywords . '%'];
            }
//            if($os)
//            {
//                $map['os'] = $os;
//            }
            if ($uid != 1) {
                $map['merchandiser'] = $uid;
                $map['status'] = array('in', '3,12');
            } else {
                $map['status'] = array('in', '3,12');
            }

            //回收显示未发货状态
            $map['huishou_status'] = ['eq','0'];

            $map['transfer'] = 0;
            $dataCount = $this->where($map)->where($map2)->count();
            $list = $this
                ->where($map)
                ->where($map2)
                ->order('status asc,third_claim_date desc,id desc')
                ->page($page, $limit)
                ->select();
            $list = modelo2array($list);
            foreach ($list as $key => $value) {
                $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);  //逾期处理
                $list[$key]['info'] = $this->statusInfo($list[$key]['status']);          //状态信息
                $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
                $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
                $list[$key]['user_admin3'] = $this->getNameById($value['treasurer']);      //财务员
                $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);   //跟单员M1
                $list[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

                $list[$key]['already_money'] = self::alreadyRepay($value, $list[$key]['status']);//已还总金额
                $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
                $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

//                $delayMoney = model('v2/Apply')->delayMoney($value);
//                $list[$key]['this_delay_money'] = $delayMoney['money_order'];  //本次延期总费
                $list[$key]['this_delay_money'] = $this->getDelayMoney($value);
            }

            $data['list'] = $list;
            $data['dataCount'] = $dataCount;
            //财务改动 线上线下配置
            $data['pay_model'] = config('PAY_MODE');
            return $data;
        }


        //当前逾期
        if ($keywords == '当前违约') {

            if ($startdate != '') {
                $startdate = substr($startdate, 0, 10);
                $startdate = date('Y-m-d', strtotime("$startdate +1 day"));

                $enddate = substr($enddate, 0, 10);
                $enddate = date('Y-m-d', strtotime("$enddate +1 day"));

                // $map['appoint_time'] = ['>',$startdate];
                // $map['appoint_time'] = ['<',$enddate];
                $map['appoint_time'] = array(['>', $startdate], ['<', $enddate]);
                $map['status'] = array('in', '4');

            } else {
                $currenttime = date('Y-m-d H:i:s', time());
                $map['appoint_time'] = ['<', $currenttime];
                $map['status'] = array('in', '4');

            }

            //回收显示未发货状态
            $map['huishou_status'] = ['eq','0'];

            $map['transfer'] = 0;
            if ($uid != 1) {
                $map['merchandiser'] = $uid;
                $map['status'] = array('in', '4');
            } else {
                $map['status'] = array('in', '4');

            }
            $dataCount = $this->where($map)->where($map2)->count();
            $list = $this
                ->where($map)
                ->where($map2)
                ->order('status asc,appoint_time desc,third_claim_date desc,id desc')
                ->page($page, $limit)
                ->select();
                // echo $this->getlastsql();
            $list = modelo2array($list);
            foreach ($list as $key => $value) {
                $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);  //逾期处理
                $list[$key]['info'] = $this->statusInfo($list[$key]['status']);          //状态信息
                $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
                $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
                $list[$key]['user_admin3'] = $this->getNameById($value['treasurer']);      //财务员
                $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);   //跟单员M1
                $list[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

                $list[$key]['already_money'] = self::alreadyRepay($value, $list[$key]['status']);//已还总金额
                $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
                $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

                $list[$key]['delay_transfer_date'] = $this->transferTime($value);  //延时移交时间

//                $delayMoney = model('v2/Apply')->delayMoney($value);
//                $list[$key]['this_delay_money'] = $delayMoney['money_order'];  //本次延期总费
                $list[$key]['this_delay_money'] = $this->getDelayMoney($value);
                $list[$key]['overdue_day'] = $this->getOverdueDay($value); //逾期天数

                //是否留案
                $list[$key]['is_liuan'] = $this->isLiuan($value);
            }

            $data['list'] = $list;
            $data['dataCount'] = $dataCount;
            //财务改动 线上线下配置
            $data['pay_model'] = config('PAY_MODE');
            return $data;
        }

        //移交订单
        if ($keywords == '移交订单') {

            if ($startdate != '') {
                $startdate = substr($startdate, 0, 10);
                $startdate = date('Y-m-d', strtotime("$startdate +1 day"));

                $enddate = substr($enddate, 0, 10);
                $enddate = date('Y-m-d', strtotime("$enddate +1 day"));

                // $map['appoint_time'] = ['>',$startdate];
                // $map['appoint_time'] = ['<',$enddate];
                $map['appoint_time'] = array(['>', $startdate], ['<', $enddate]);
            }

            if ($uid != 1) {
                $map['merchandiser'] = $uid;
            } else {
            }
            $map['status'] = array('in', '3,4,5,12');

            //回收显示未发货状态
            $map['huishou_status'] = ['eq','0'];

            $map['transfer'] = 1; //移交
            $dataCount = $this->where($map)->count();
            $list = $this
                ->where($map)
                ->order('status asc,third_claim_date desc,id desc')
                ->page($page, $limit)
                ->select();
            $list = modelo2array($list);
            foreach ($list as $key => $value) {
                $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);  //逾期处理
                $list[$key]['info'] = $this->statusInfo($list[$key]['status']);          //状态信息
                $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
                $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
                $list[$key]['user_admin3'] = $this->getNameById($value['treasurer']);      //财务员
                $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);   //跟单员M1
                $list[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

                $list[$key]['already_money'] = self::alreadyRepay($value, $list[$key]['status']);//已还总金额
                $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
                $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

                $list[$key]['delay_transfer_date'] = $this->transferTime($value);  //延时移交时间

//                $delayMoney = model('v2/Apply')->delayMoney($value);
//                $list[$key]['this_delay_money'] = $delayMoney['money_order'];  //本次延期总费
                $list[$key]['this_delay_money'] = $this->getDelayMoney($value);
            }

            $data['list'] = $list;
            $data['dataCount'] = $dataCount;
            //财务改动 线上线下配置
            $data['pay_model'] = config('PAY_MODE');
            return $data;
        }

        if($keywords == '返回订单'){
            if ($valuedate != '') {
                $startdate = substr($valuedate, 0, 10);
                $startdate = date('Y-m-d', strtotime("$valuedate +1 day"));

                $enddate = substr($enddate, 0, 10);
                $enddate = date('Y-m-d', strtotime("$enddate +1 day"));

                // $map['appoint_time'] = ['>',$startdate];
                // $map['appoint_time'] = ['<',$enddate];
                $map['c.create_time'] = array('between',array($startdate,$enddate));
            }
            if($os){
                $map['a.os'] = $os;
            }
            if ($uid != 1) {
                $map['a.merchandiser'] = $uid;
            }
            if($status){
                $map['a.status'] = $status;
            }
            $map['huishou_status'] = 3;
            $map['a.transfer'] = 0;
            $data = $this->alias('a')
                ->join('consignment c','a.order_number=c.apply_id')
                ->join('admin_user u','a.huishou_aid=u.id')
                ->field('a.id,c.create_time time,a.order_number,a.name,a.phone,u.realname  huishou_aid,a.huishou_status,a.delay_transfer_date,a.fk_time,a.appoint_time,a.money,a.status')
                ->where($map)
                ->order('c.create_time desc')
                ->select();
//            echo $this->getLastSql();exit;
            $dataCount = $this->alias('a')
                ->join('consignment c','a.order_number=c.apply_id')
                ->join('admin_user u','a.huishou_aid=u.id')
                ->field('a.order_number')
                ->where($map)
                ->group('a.order_number')
                ->select();
            $data = modelo2array($data);
            $status= array('申请中','初审通过','复审通过','已放款','逾期中','已完成','初审驳回','复审驳回','其他驳回','回访通过','回访拒绝','拒绝放款','延期');
            $room = array();
            foreach ($data as $key => $value){

                $days = $this->getOverdueDay($value);
                $data[$key]['overdue_days'] = $days;
                $data[$key]['overdue_money'] = $days*0.11*$value['money'];

                if(!isset($room[$value['order_number']])){
                    $room[$value['order_number']] = $key;
                }elseif (isset($room[$value['order_number']]) && strtotime($value['time'])>strtotime($data[$room[$value['order_number']]]['time'])){

                    unset($data[$room[$value['order_number']]]);
                    $room[$value['order_number']] = $key;
                }else{
                    unset($data[$key]);
                }
            }
            foreach ($data as $key => $value){
                $data[$key]['status'] = $status[$value['status']];
            }
            $list['list'] = $data;
            $list['dataCount'] = count($dataCount);
            //财务改动 线上线下配置
            $list['pay_model'] = config('PAY_MODE');
            return $list;




        }
        //全部跟单
        $map = array();
        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate +1 day"));
            $map['time'] = ['like', '%' . $valuedate . '%'];
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }
        if ($os) {
            $map['os'] = $os;
        }
        if ($uid != 1) {
            $map['merchandiser'] = $uid;
        } else {
            $map['status'] = array('in', '2,3,4,5,9,10,11,12');
        }
        if (in_array($status, [2, 3, 4, 5, 9, 10, 11, 12])) {
            $map2['status'] = $status;
        }

        //回收显示未发货状态
        $map['huishou_status'] = ['eq','0'];

        $map['transfer'] = 0;
        $dataCount = $this->where($map)->where($map2)->count();


        $list = $this
            ->where($map)
            ->where($map2)
            ->order($order)
            ->page($page, $limit)
            ->select();
        $list = modelo2array($list);
        foreach ($list as $key => $value) {
            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);  //逾期处理
            $list[$key]['info'] = $this->statusInfo($list[$key]['status']);          //状态信息
            $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
            $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
            $list[$key]['user_admin3'] = $this->getNameById($value['treasurer']);      //财务员
            $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);   //跟单员M1
            $list[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

            $list[$key]['already_money'] = self::alreadyRepay($value, $list[$key]['status']);//已还总金额
            $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
            $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

            $list[$key]['delay_transfer_date'] = $this->transferTime($value);  //延时移交时间

//            $delayMoney = model('v2/Apply')->delayMoney($value);
//            $list[$key]['this_delay_money'] = $delayMoney['money_order'];  //本次延期总费

            $list[$key]['this_delay_money'] = $this->getDelayMoney($value);

            //是否留案
            $list[$key]['is_liuan'] = $this->isLiuan($value);

            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 2;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }


        }

        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        //财务改动 线上线下配置
        $data['pay_model'] = config('PAY_MODE');
        return $data;
    }
    /**
     * @param $keywords  [搜索关键词]
     * @param $page      [页码]
     * @param $limit     [每页数]
     * @param $condition [筛选条件] //SUCCESS  OR FAILURE
     * @param $time      [筛选条件] // datetiem
     * @AUTHER 范俊成
     * @DATE 2018/4/4
     */
    public function get_history($keywords,$page,$limit,$time='',$condition='')
    {
//        $time='2018-04-02T16:00:00.000Z';

//        $keywords='2018021249102485';
//        $condition='SUCCESS';
        if($keywords=='回收历史记录'){
            $keywords='';
        }

        $start = empty($time)?'': date('Y-m-d H:i:s',strtotime($time));
        $end   = empty($time)?'':date('Y-m-d H:i:s',strtotime($time)+24*60*60);
        $admin_id   =   $GLOBALS['userInfo']['id'];
        $offset = $page==1?0:($page-1)*$limit;


        $sql=' select p.result_pay,a.time,p.type,p.update_time,a.name,a.phone,p.ret_msg,u.username,a.loan_out_money from qh_apply a inner join qh_payment_order p on a.order_number=p.apply_id left join qh_admin_user u  on a.merchandiser=u.id where result_pay is not null';
        $sql1='select count(*) from qh_apply a inner join qh_payment_order p on a.order_number=p.apply_id  left join qh_admin_user u  on a.merchandiser=u.id where p.result_pay is not null ';
        if(preg_match('/^\d{11}$/',$keywords)){
            $sql=$sql.' and  a.phone='.$keywords;   //如果是11位纯数字就是手机号
            $sql1=$sql1.' and  a.phone='.$keywords;   //如果是11位纯数字就是手机号
        }elseif(preg_match('/^\d{16}$/',$keywords)){
            $sql=$sql.' and  a.order_number='.$keywords;//如果是16位纯数字就是订单号
            $sql1=$sql1.' and  a.order_number='.$keywords;//如果是16位纯数字就是订单号
        }elseif($keywords==''){
            $sql=$sql;                                      //如果是空就是没有条件
        }else{
            $sql=$sql." and  a.name='$keywords'";   //剩下的就是默认是按姓名查找
            $sql1=$sql1." and  a.name='$keywords'";   //剩下的就是默认是按姓名查找
        }

        if(!empty($time)){

            $sql=$sql." and p.update_time between '$start' and '$end'  ";
            $sql1=$sql1." and p.update_time between '$start' and '$end'  ";

        }
        if(!empty($condition)){

            $sql = $sql." and p.result_pay='$condition' ";
            $sql1 = $sql1." and p.result_pay='$condition' ";



        }
//        $admin_id=1;
        if($admin_id == 1){
            $sql=$sql.'  order by p.update_time desc limit '.$limit.' offset '.$offset;  //如果是管理员就默认可以看到全部
            $sql1=$sql1.'  order by p.update_time desc ';  //如果是管理员就默认可以看到全部
        }else{

            $sql=$sql.'  and a.merchandiser='.$admin_id.' order by p.update_time desc limit '.$limit.' offset '.$offset;  //否则只能看到自己的
            $sql1=$sql1.'  and a.merchandiser='.$admin_id.' order by p.update_time desc  ';  //否则只能看到自己的

        }
//       echo $sql;exit;
//        echo $sql1;exit;

        $result = $this->query($sql);  #三表联查有待优化
        $count  = $this->query($sql1);
//        var_dump($result);exit;
//        var_dump($count);exit;
        $result['list']=$result;
        $result['dataCount']=$count[0]['count(*)'];
        return $result;

    }




    /**
     * 自动移交时间
     * @author cxr <1481746137@qq.com>
     */
    public function transferTime($value){

        if(!$value['overdue_date'])
            return;

        $will = !$this->isLiuan($value) ? $value['delay_transfer_date'] : $value['appoint_time'];
        $onTime = strtotime('+1 day', strtotime($will));
//        $time =  date('Y-m-d H:i:s', $onTime);

        $time =  date('Y-m-d', $onTime);
        $time = date('Y-m-d H:i:s',strtotime('+23hours',strtotime( $time ) + 3540));

        return $time;
    }

    /**
     * 能否留案
     * @author cxr <1481746137@qq.com>
     */
    public function isLiuan($value){
        if(empty($value['delay_transfer_date'])){
            return true;
        }
        $date = strtotime($value['delay_transfer_date']);
        $time = date('Y-m-d',$date);
        if(strtotime($time) <= strtotime($value['appoint_time']) ){
            return true;
        }
        return false;
    }

    /**
     * 已还金额
     * @author cxr <1481746137@qq.com>
     * @param $applyid
     * @param $status
     * @param $total
     * @return float|int
     */
    static public function alreadyRepay($value, $status)
    {
        if (in_array($status, [5])) {
//            $map['apply_id'] = $value['order_number'];
//            $map['result_pay'] = 'SUCCESS';
//            $map['no_order'] = ['notlike', '%XQ%']; //不和延期订单混淆， 失误少了个这个条件
//            $repayLog = Db::name('user_order')->where($map)->order('pay_time desc')->find();
//            return $repayLog['money_order'] + $value['part_repay'];
            return $value['actual_money'] + $value['part_repay'];
        }

//        $reminder = model('Reminder');
//        $money = $reminder->where(['apply_id' => $applyid])->sum('repay_money');
        #已还金额 = 每次待还金额
        return $value['actual_money'] + $value['part_repay'];
//        if ($money != NULL) {
//            return $money;
//        } else {
//            return 0.0;
//        }

    }

    /**
     * 回访报表
     * @author cxr <1481746137@qq.com>
     * @param $start
     * @param $end
     * @return mixed
     */
    public function getReport($start, $end,$page)
    {
        if (!$start) {

            $start_date = date('Y-m-d', time());
            $start = $start_date . ' 00:00:00';
            $end_date = date('Y-m-d', time() + 24 * 60 * 60);
            $end = $end_date . ' 00:00:00';

        }
        $date = array('BETWEEN', [$start, $end]);  //时间段

        $map['monepassdate'] = $date;
        if($GLOBALS['userInfo']['id'] != 1)
        {
            $map['merchandiser'] = $GLOBALS['userInfo']['id'];
        }

        $info = $this->where($map)->order('status asc,id desc')->page($page, $limit)->fetchSql(false)->select();
        foreach ($info as $key => $value)
        {
            $info[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);  //催收员M2
        }

        $count = $this->where($map)->count();  //当天处理总数
        $count_x = $this->where($map)->where('status = 10')->count();
        if (!$count) {
            $rate_pass = 0;
        } else {
            $rate_pass = (($count - $count_x) / $count) * 100;
            $rate_pass = substr($rate_pass, 0, 5);
        }
        $data['info'] = $info;
        $data['rate_pass'] = $rate_pass;
        $data['dataCount'] = $count;
        return $data;

    }

    /**
     * 功能:  [催收报告]
     * @Author   wjf
     * @email    605993145@qq.com
     * @DateTime 2018-03-01
     * @param    [type]           $start [开始时间]
     * @param    [type]           $end   [结束时间]
     * @return   [type]                  [description]
     */
    public function collectionReport($start, $end,$page)
    {
        if (!$start) {

            $start_date = date('Y-m-d', time());
            $start = $start_date . ' 00:00:00';
            $end_date = date('Y-m-d', time() + 24 * 60 * 60);
            $end = $end_date . ' 00:00:00';

        }
        $date = array('BETWEEN', [$start, $end]);  //时间段

        $map['fourth_claim_date'] = $date;
        if($GLOBALS['userInfo']['id'] != 1)
        {
            $map['merchandiser2'] = $GLOBALS['userInfo']['id'];
        }

        $info = $this->where($map)->order('status asc,id desc')->page($page, $limit)->fetchSql(false)->select();
        // echo $this->getlastsql();
        foreach ($info as $key => $value)
        {
            $info[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

            //催收还款金额 
            $orderWhere1['apply_id'] = $value['order_number'];
            $orderWhere1['result_pay'] = 'SUCCESS';
            $orderWhere1['pay_time'] = ['>',$value['fourth_claim_date']];
            $moneyArr1 = Db::name('user_order')->field('pay_type,type,pay_time,money_order')->where($orderWhere1)->order('id desc')->select();
            foreach ($moneyArr1 as $k => $v) {
                $money_order_sum +=$v['money_order'];
            }
            $info[$key]['money_order'] = $money_order_sum;
            unset($money_order_sum);
            
            //支付时间
            $info[$key]['pay_time'] = $moneyArr1[0]['pay_time'];
            //催收结果
            $info[$key]['type'] = $moneyArr1[0]['type'];
            //线下/线上
            $info[$key]['pay_type'] = $moneyArr1[0]['pay_type'];
        }

        $count = $this->where($map)->count();  //总数
        $count_x = $this->where($map)->where('status = 5 or status = 12')->count();

        if (!$count) {
            $rate_pass = 0;
        } else {
            $rate_pass = ($count_x / $count) * 100;
            $rate_pass = substr($rate_pass, 0, 5);
        }

        //催收总额
        $infoMoney = Db::name('apply')->field('fourth_claim_date,order_number')->where($map)->select();

        foreach ($infoMoney as $key => $value)
        {
            $orderWhere['apply_id'] = $value['order_number'];
            $orderWhere['result_pay'] = 'SUCCESS';
            $orderWhere['pay_time'] = ['>',$value['fourth_claim_date']];
            $moneyArr = Db::name('user_order')->field('money_order')->where($orderWhere)->select();
            foreach ($moneyArr as $k => $v) {
                $sumMoney +=$v['money_order'];
            }
            
            unset($infoMoney[$key]);
        }
        $data['info']       = $info;
        $data['rate_pass']  = $rate_pass;
        $data['dataCount']  = $count;
        $data['sumMoney']   = $sumMoney;
        return $data;
    }

    /**
     * 应还日期、放款时间和当前日期对比
     * @param  [string] $fk_time      [放款日期]
     * @param  [string] $appoint_time [应还日期]
     * @return [array]  $data         [description]
     */
    public function timeStatus($fk_time, $appoint_time) {
        $overdue_day = $advance_day = $cost_day = 0;
        $info   = '未知';
        $status = '-1';

        if(!empty($fk_time)){
            if(!defined(SYS_TIMESTAMP))
            {
                define(SYS_TIMESTAMP,time());
            }
            $date_now     = date("Y-m-d",SYS_TIMESTAMP);                     
            $date_fk      = date("Y-m-d", strtotime($fk_time));       
            $date_appoint = date("Y-m-d", strtotime($appoint_time));  

            $day = (strtotime($date_now) - strtotime($date_appoint)) /(24*3600);    //提前或逾期天数

            $cost_day = (strtotime($date_now)-strtotime($date_fk))/(24*3600);
            $cost_day = $cost_day == 0 ? 1 : $cost_day ;    //已借天数 不足一天算一天

            $cost_info = '已借款'.$cost_day.'天';
            if($day>0){
                $info = '逾期'.$day.'天';
                $status = '2';
                $overdue_day = $day;
            }elseif($day<0){
                $day = abs($day);
                $info = '提前'.$day.'天';
                $status = '1';
                $advance_day = $day;
            }elseif($day==0){
                $info = '正常';
                $status = '0';
            }
        }

        $data = array(
            'status'       => $status,       //状态 -1:未知 0:正常 1:提前 2:逾期
            'info'         => $info,         //描述
            'overdue_day'  => $overdue_day,  //逾期天数
            'advance_day'  => $advance_day,  //提前天数
            'cost_day'     => $cost_day,     //已借天数
            'cost_info'    => $cost_info,    //已借天数描述
            'date_now'     => $date_now,     //现在日期
            'date_fk'      => $date_fk,      //放款日期
            'date_appoint' => $date_appoint, //应还日期
        );   

        return $data;
    }

    /**
     * 移交客户
     * @author   湛慧平 <1013619199@qq.com>
     * @DateTime 2017-08-10
     * @param
     */
    public function Transferinfo($param)
    {
        $admin_uid = $GLOBALS['userInfo']['id'];
        $transfer_info = $param['opinion'];
        $uid = $param['uid'];
        $id = $param['id'];
        $map['id'] = $id;
        $date = date("Y-m-d H:i:s", time());

        $data = ['transfer_info' => $transfer_info, 'transfer' => 1, 'm1_yijiao_date' => $date];
        $admin_data = ['uid' => $uid, 'authstatus' => 4, 'admin_user_id' => $admin_uid, 'status' => 2, 'apply_id' => $id, 'date' => $date];
        $admin_info = Db::name('admin_user_clien')->insert($admin_data);
        if (!$admin_info) {
            $this->error = "没有保存";
            return false;
        }

        $info = $this->save($data, $map);
        if (!$info) {
            $this->error = "移交失败";
            return false;
        }

        return true;

    }

    /**
     * 延时移交/留案
     * @author cxr <1481746137@qq.com>
     * @param $param
     * @return bool
     * @throws \think\exception\DbException
     */
    public function delayTransfer($param)
    {

        $info = self::get(['id' => $param['id']]);
//        $hours = config('DELAY_TRANSFER_HOUR');
        $hours = $param['hours'] * 24;

        if ($this->isLiuan($info)) {
            $delay = strtotime("+{$hours} hours", strtotime($info->appoint_time));
        } else {
//            $delay = strtotime("+{$hours} hours", strtotime($info->delay_transfer_date));
            $this->error = "已留案,不能重复留案!";
            return false;
        }

        $date = date('Y-m-d H:i:s', $delay);
        $info->delay_transfer_date = $date;

        if (!$info->save()) {
            $this->error = "延时移交失败";
            return false;
        }
        return true;
    }



    /**
     * 后台确认还款
     * @author   湛慧平 <1013619199@qq.com>
     * @DateTime 2017-08-10
     * @param
     */
    public function repayment($param)
    {

        if(!$param['smsVerification_s'] || strlen($param['smsVerification_s']) != 4 ){
            return resultArray(["error" => '验证码错误1']);
        }
        $user_id = $GLOBALS['userInfo']['id'];
        $res = Db::name('smsverification')->where(['user_id'=>$user_id])->field('smsVerification,create_date')->find();
        if($param['smsVerification_s'] != $res['smsVerification'] || (time() > (strtotime($res['create_date'])+(config('sms_aging')['sms_aging'])))){
              return resultArray(["error" => '验证码错误2']);
        }
        $uid = $param['uid'];
        $wheres['uid'] = $uid;
        $admin_uid = $GLOBALS['userInfo']['id'];
        $id = $param['id'];
        $map['id'] = $id;
        $time = date('Y-m-d H:i:s', time());

        if(!is_numeric( $param['actual_money'] ) || $param['actual_money'] <= 0 || !preg_match('/^[0-9]+(.[0-9]{1,2})?$/',$param['actual_money'])){
            $this->error = '金额过少或金额格式有误';
            return false;
        }

        //当天不能线下还款
        $where['uid'] = $uid;
        $where['time'] = ['egt',date('Y-m-d')];
        $where['status'] = 3;
        $count = $this->where($where)->count('id');
        if($count > 0)
        {
            $this->error = "放款当天不能线下还款";
            return false;
        }
        $res = $this->where('id', $id)->find();
        $actual_money       = empty($res['actual_money'])? '0' : $res['actual_money']; //实际还款金额
        $cur_money          = empty($res['cur_money']) ? $res['money'] : $res['cur_money']; // 应还本金 2018/2/27
        $dataA['cur_money'] = $cur_money;


        $maps = ['apply_id' => $id, 'authstatus' => 4, 'revoked' => 1];
        $admin_userdata = Db('admin_user_clien')->where($maps)->field('admin_user_id')->find();
        $admin_data = ['uid' => $uid, 'admin_user_id' => $admin_userdata['admin_user_id'],
            'apply_id' => $id, 'status' => 3, 'date' => $time, 'authstatus' => 4];


        //还款插入订单 公共数据
        $dataO['apply_id'] = $res['order_number'];
        $dataO['create_time'] = date('Y-m-d H:i:s');
        $dataO['period'] = $res['period'];
        $dataO['type'] = $param['pay_type']; //还款方式 1：全额还款  2：延期  3：部分还款
        $dataO['no_order'] = 'M1HT';

        $dataO['acct_name'] = $res['name'];
        $dataO['id_no'] = $res['id_card'];
        $dataO['pay_time'] = date('Y-m-d H:i:s');
        $dataO['pay_type'] = 'XX';
        $dataO['money_order'] = $param['actual_money'];
        $dataO['result_pay'] = 'SUCCESS';
        $dataO['delay_aid'] = $admin_uid;
        $dataO['info_order'] = $param['pay_type'] == 1?'后台全额还款':'后台部分还款';


        if($param['pay_type'] == 3){ // 部分还款

//            $gearModel    = new Gear;
//            $apply_status = $gearModel->apply_status($res);
//            if($apply_status['part']!=1){
//                $this->error = '逾期后才能部分还款';
//                return false;
//            }
//            if($arr['money_order'] < 100 && $param['pay_money'] != $arr['money_order']){
//                $this->error = '金额过少不支持修改';
//                return false;
//            }
//            if($arr['money_order'] > 100 && $param['pay_money'] < 100) {
//                $this->error = '金额不能少于100';
//                return false;
//            }
//            if($param['pay_money'] > $arr['money_order']){
//                $this->error = '大于应还金额';
//                return false;
//            }

            $arr = (new Apply())->loanMoney($res);
            if($param['actual_money'] >= $arr['money_order']){ // 部分还款 一次性归还
                $dataA['cur_money'] = 0;  //应还本金

            }else{
                // 应还本金 = 应还金额 - 此次支付费用
                $dataA['cur_money'] = $arr['money_order'] - $param['actual_money'];
                $dataA['part_date'] = date('Y-m-d H:i:s');  //部分还款时间
            }
        }else{ //全额还款
//            $dataA['cur_money'] = 0;  //应还本金
        }

        //应还本金为0时结束订单或全额还款
        if($dataA['cur_money'] <= 0 || $param['pay_type'] == 1){
            $dataA['status']    = 5; //申请单状态改为 还款成功5
            $dataA['hk_time']   = date('Y-m-d H:i:s');  //还款时间
            $param['pay_type'] == 3 && $dataA['cur_money'] = 0;  //部分还款应还本金

            // 无逾期并且还款成功 自动升级档位
            if ($res['overdue_count'] < 1) {
                $OrderModel = new Order;
                $dataU['max_money'] = $OrderModel->nextMoney($res);
            }
        }
        $dataA['actual_money'] = $actual_money + $param['actual_money'];  //实际还款金额



        $this->startTrans();
        try {
            $info = $this->save($dataA, $map);
            $info = Db::name('admin_user_clien')->insert($admin_data);

            $dataU['update_time'] = date('Y-m-d H:i:s');
            $info = Db::name('user_info')->where($wheres)->update($dataU);

            $info = Db::name('user_order')->insert($dataO);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            //事物回滚
            $this->rollback();
            $this->error = "确认还款失败";
            return false;
        }

    }

    /**
     * 延期预览金额及日期
     * @author cxr <1481746137@qq.com>
     * @param $id
     * @return mixed
     */
    public function getdelay($param){
        if(!$param['smsVerification_s'] || strlen($param['smsVerification_s']) != 4 ){
            return resultArray(["error" => '验证码错误1']);
        }
        $user_id = $GLOBALS['userInfo']['id'];
        $res = Db::name('smsverification')->where(['user_id'=>$user_id])->field('smsVerification,create_date')->find();
        if($param['smsVerification_s'] != $res['smsVerification'] || (time() > (strtotime($res['create_date'])+(config('sms_aging')['sms_aging'])))){
              return resultArray(["error" => '验证码错误2']);
        }
        $res = $this->where('id', $param['id'])->find();

        if($res['zhangqi']==1 && $param['days']==7){
            $this->error='不能重复展期';
            return false;
        }

        #延期种类对应金额（4种 1 2 3 7） 2018 3/9
        $delayMoney = model('v2/Apply');
        $delayMoneyOrder = $delayMoney->delayMoney($res->toArray(),$param['days']);
        if(!$delayMoneyOrder){
            $this->error= $delayMoney->getError();
            return false;
        }

        $appoint_time = $res['appoint_time'];   //约定还款时间
        $period = $param['days']; //借款周期

        $period = $param['days']; //借款周期

        if(strtotime(date("Y-m-d H:i:s", strtotime($appoint_time))) > strtotime(date("Y-m-d H:i:s"))){
            $startTime = strtotime( $appoint_time );
            $data['type'] = '正常';
        }else{
            $startTime =  time();
            $data['type'] = '逾期';
        }
        $data['delayDate'] = date("Y-m-d H:i:s", $startTime + $period*24*3600);
        $data['delayDate2']  = date('Y-m-d H:i:s', $appoint_time + $period*24*3600); //延期后归还日期






        $data['delayMoney'] = $delayMoneyOrder['money_order']; //延期后归还金额

        return $data;
    }


    /**
     * 后台延期操作
     * @return [type] [description]
     */
    public function delay($param)
    {
        //延期天数
        $days = $param['days'];

        $uid = $param['uid'];
        $wheres['uid'] = $uid;
        $admin_uid = $GLOBALS['userInfo']['id'];
        $id = $param['id'];
        $map['id'] = $id;
        $time = date('Y-m-d H:i:s', time());

        $maps = ['apply_id' => $id, 'authstatus' => 4, 'revoked' => 1];
        $admin_userdata = Db('admin_user_clien')->where($maps)->field('admin_user_id')->find();
        $admin_data = ['uid' => $uid, 'admin_user_id' => $admin_userdata['admin_user_id'],
            'apply_id' => $id, 'status' => 4, 'date' => $time, 'authstatus' => 4];

        $res = $this->where('id', $id)
//            ->field('delay_money,renewal_count,id,name,id_card,period,order_number,money,cur_money,appoint_time')
            ->find();
        $delay_money = empty($res['delay_money']) ? '0' : $res['delay_money'];
        $renewal_count = empty($res['renewal_count']) ? '0' : $res['renewal_count'];
        $appoint_time = $res['appoint_time'];   //约定还款时间


        // 3/9
        if($res['zhangqi']==1 && $param['days']==7){
            $this->error='不能重复展期';
            return false;
        }

        #延期种类对应金额（4种 1 2 3 7） 2018 3/9
        $delayMoney = model('v2/Apply');
        $delayMoneyOrder = $delayMoney->delayMoney($res->toArray(),$param['days']);
        if(!$delayMoneyOrder){
            $this->error= $delayMoney->getError();
            return false;
        }
        $money_order = $delayMoneyOrder['money_order']; //当前延期费用

        #延期天数（4种 1 2 3 7）2018/3/9
        $period = $days;
//        $dataA['appoint_time']  = date('Y-m-d H:i:s', $appoint_time + $period*24*3600);
        // 延期到什么时候  2018/3/23
        if(strtotime(date("Y-m-d", strtotime($appoint_time))) > strtotime(date("Y-m-d"))){
            $startTime = strtotime($appoint_time);
        }else{
            $startTime = time();
        }
        $dataA['appoint_time'] = date("Y-m-d", $startTime + $period*24*3600);

        $dataA['delay_money'] = $delay_money + $money_order;//总延期费用
        $dataA['status'] = 12; //延期状态
        $dataA['renewal_count'] = $renewal_count + 1;//总延期次数

        $dataO['money_order'] = $money_order;
        $dataO['apply_id'] = $res['order_number'];
        $dataO['no_order'] = 'XQ';
        $dataO['acct_name'] = $res['name'];
        $dataO['id_no'] = $res['id_card'];
        $dataO['create_time'] = date('Y-m-d H:i:s');
        $dataO['pay_time'] = date('Y-m-d H:i:s');
        $dataO['pay_type'] = 'XX';
        $dataO['info_order'] = '线下延期 延期次数:' . $dataA['renewal_count'];
        $dataO['result_pay'] = 'SUCCESS';
        $dataO['delay_aid'] = $admin_uid;
        $dataO['period'] = $period;

        // 3/15 还款方式 1：全额还款  2：延期  3：部分还款
        $dataO['type'] = 2;


        // 改这里
        // 应还本金 2018/2/27
        $dataU = [];
        $cur_money = empty($res['cur_money']) ? $res['money'] : $res['cur_money'];
        $dataA['cur_money'] = $cur_money;

        // 延期7天 才扣除本金的20%  2017/3/8
        if($period == 7){
            $dataA['cur_money'] = formatMoney($cur_money - $cur_money * 0.2);
            if($dataA['cur_money'] == $cur_money){ //特殊处理0.05
                $dataA['cur_money'] = $dataA['cur_money'] - 0.01;
            }
            //展期
            $dataA['zhangqi'] = 1;

            //部分还款 2018 3/9
            $dataA['part_repay'] = formatMoney($res['part_repay'] + $cur_money * 0.2);
        }

        //2018 3/9
        if ($dataA['cur_money'] <= 0) { //应还本金为0时结束订单
            $dataA['cur_money'] = 0;
            $dataA['status'] = 5; //申请单状态改为 还款成功5
            // 无逾期并且还款成功 自动升级档位
            if ($res['overdue_count'] < 1) {
                $OrderModel = new Order;
                $dataU['max_money'] = $OrderModel->nextMoney($res);
            }
        }




        $this->startTrans();
        try {
            $info = $this->save($dataA, $map);
            $info = Db::name('admin_user_clien')->insert($admin_data);
            $info = Db::name('user_order')->insert($dataO);
            $info = Db::name('user_info')->where($wheres)->update($dataU);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            //事物回滚
            $this->rollback();
            $this->error = "延期失败" . $e->getMessage();
            return false;
        }

    }


    /**
     * 确认保存备注
     * @author   湛慧平 <1013619199@qq.com>
     * @DateTime 2017-08-10
     * @param
     */
    public function saveinfo($param)
    {
        $admin_uid = $GLOBALS['userInfo']['id'];
        $apply_id = $param['id'];
        $is_friend = $param['is_friend'];
        $is_loans = $param['is_loans'];
        $discount = $param['discount'];
        $uid = $param['uid'];
        $create_time = date('Y-m-d H:i:s', time());
        $data = [
            'admin_id' => $admin_uid, 'uid' => $uid,
            'remarks' => $discount, 'is_friends' => $is_friend,
            'is_loans' => $is_loans, 'create_time' => $create_time,
            'apply_id' => $apply_id
        ];
        $map['apply_id'] = $apply_id;
        $info = Db::name('apply_bz')->field('apply_id')->where($map)->find();

        if ($info) {
            $data = Db::name('apply_bz')->where($map)->update($data);
            if (!$data) {
                $this->error = "存取失败";
                return false;
            }
            return true;
        }

        $data = Db::name('apply_bz')->insert($data);
        if (!$data) {
            $this->error = "存取失败";
            return false;
        }
        return true;
    }


    //查找保存的备注结果
    public function selectinfo($param)
    {
        $map['id'] = $param['id'];
        $info = Db::name('apply_bz')->field('is_friends,is_loans,remarks')->where($map)->find();
        if (!$info) {
            $this->error = "获取失败";
            return false;
        }
        return $info;
    }

    //M1保存催收日志
    public function remindernote($param)
    {
        $admin_uid = $GLOBALS['userInfo']['id'];
        $uid = $param['uid'];
        $id = $param['id'];
        $contact_name = $param['contact_name'];
        $reminder_status = $param['reminder_status'];
        $appoint_time = $param['appoint_time'];
        $appointtime = strtotime($appoint_time);
        $status = $param['status'];
        $contact_type = $param['contact_type'];
        $repay_money = empty($param['repay_money'])?0:$param['repay_money'];

        if (time() > $appointtime && $status == 4) {
            $time = (time() - $appointtime) / (60 * 60 * 24);
            $days_overdue = intval($time) + 1;
        } else {
            $days_overdue = 0;
        }

        $reminder_time = date('Y-m-d H:i:s', time());

        $data = [
            'admin_uid' => $admin_uid,
            'uid' => $uid,
            'apply_id' => $id,
            'contact_name' => $contact_name,
            'reminder_status' => $reminder_status,
            'days_overdue' => $days_overdue,
            'reminder_time' => $reminder_time,
            'reminder_character' => 'M1',
            'contact_type' => $contact_type,
            'repay_money' => $repay_money
        ];

        $info = Db::name('reminder_note')->insert($data);
        if (!$info) {
            $this->error = "失败";
            return false;
        }
        return true;
    }


    /**
     * 功能:  [催收报告]
     * @Author   wjf
     * @email    605993145@qq.com
     * @DateTime 2018-03-01
     * @param    [type]           $start [开始时间]
     * @param    [type]           $end   [结束时间]
     * @return   [type]                  [description]
     */
    public function mtwocollectionReport($start, $end,$page)
    {
        if (!$start) {

            $start_date = date('Y-m-d', time());
            $start = $start_date . ' 00:00:00';
            $end_date = date('Y-m-d', time() + 24 * 60 * 60);
            $end = $end_date . ' 00:00:00';

        }
        $date = array('BETWEEN', [$start, $end]);  //时间段

        $map['fifth_claim_date'] = $date;
        if($GLOBALS['userInfo']['id'] != 1)
        {
            $map['mtwo_admin_user_id'] = $GLOBALS['userInfo']['id'];
        }

        $info = $this->where($map)->order('status asc,id desc')->page($page, $limit)->fetchSql(false)->select();
        // echo $this->getlastsql();
        foreach ($info as $key => $value)
        {
            $info[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2
            if($value['mtwotransfer'] == 1)
            {
                $info[$key]['user_admin5'] = $this->getNameById($value['mtwo_admin_user_id']);  //催收员M2
            }
            //催收还款金额
            $orderWhere1['apply_id'] = $value['order_number'];
            $orderWhere1['result_pay'] = 'SUCCESS';
            $orderWhere1['pay_time'] = ['>',$value['fifth_claim_date']];
            $moneyArr1 = Db::name('user_order')->field('pay_type,type,pay_time,money_order')->where($orderWhere1)->order('id desc')->select();
            foreach ($moneyArr1 as $k => $v) {
                $money_order_sum +=$v['money_order'];
            }
            $info[$key]['money_order'] = $money_order_sum;
            unset($money_order_sum);

            //支付时间
            $info[$key]['pay_time'] = $moneyArr1[0]['pay_time'];
            //催收结果
            $info[$key]['type'] = $moneyArr1[0]['type'];
            //线下/线上
            $info[$key]['pay_type'] = $moneyArr1[0]['pay_type'];
        }

        $count = $this->where($map)->count();  //总数
        $count_x = $this->where($map)->where('status = 5 or status = 12')->count();

        if (!$count) {
            $rate_pass = 0;
        } else {
            $rate_pass = ($count_x / $count) * 100;
            $rate_pass = substr($rate_pass, 0, 5);
        }

        //催收总额
        $infoMoney = Db::name('apply')->field('fifth_claim_date,order_number')->where($map)->select();

        foreach ($infoMoney as $key => $value)
        {
            $orderWhere['apply_id'] = $value['order_number'];
            $orderWhere['result_pay'] = 'SUCCESS';
            $orderWhere['pay_time'] = ['>',$value['fifth_claim_date']];
            $moneyArr = Db::name('user_order')->field('money_order')->where($orderWhere)->select();
            foreach ($moneyArr as $k => $v) {
                $sumMoney +=$v['money_order'];
            }

            unset($infoMoney[$key]);
        }
        $data['info']       = $info;
        $data['rate_pass']  = $rate_pass;
        $data['dataCount']  = $count;
        $data['sumMoney']   = $sumMoney;
        return $data;
    }



    public function getOverruleList($uid, $keywords, $page=1, $limit=15, $valuedate, $os = '',$status = "")
    {
        if($valuedate)
        {
            $valuedate = substr($valuedate,0,10);
            $valuedate = date('Y-m-d',strtotime("$valuedate +1 day"));
            $map['a.huishou_time'] = ['like', '%'.$valuedate.'%'];
        }

        if($os)
        {
            $map['a.os'] = $os;
        }
        if($uid != 1)
        {
            $map['a.mtwo_admin_user_id'] = $uid;
        }

        $map['a.huishou_status'] = 3;
        $map['a.mtwotransfer'] = 1;


        $data = $this->alias('a')->join('consignment c','a.order_number=c.apply_id')->join('admin_user u','a.huishou_aid=u.user_id')->field('c.create_time time,a.name,a.phone,u.username huishou_aid,a.huishou_status,a.delay_transfer_date,a.fk_time,a.appoint_time,a.money')->where($map)->select();
        $dataCount = $this->alias('a')->join('consignment c','a.order_number=c.apply_id')->join('admin_user u','a.huishou_aid=u.user_id')->field('count(*)')->where($map)->select();

        $data = modelo2array($data);
        foreach ($data as $k => $v){
            $days = time()-strtotime($v['appoint_time']);
            if($days > 0){
                $days = ceil($days/(3600*24));
                $data[$k]['overdue_days'] = $days;
                $data[$k]['overdue_money'] = $days*0.11*$v['money'];
            }else{
                $data[$k]['overdue_days'] = 0;
                $data[$k]['overdue_money'] = 0;
            }
            $data[$k]['status'] = '驳回';
        }

        $list['list'] = $data;
        $list['dataCount'] = $dataCount[0]['count(*)'];
        return $list;



    }

    /**
     * 移交至回收列表
     * @param $id
     * @return bool
     * @throws \think\exception\PDOException
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/5/23
     */
    public function transferToRecoveryList($id)
    {
        $data['huishou_status'] = 1;
        $data['huishou_claim_date'] = null;
        $data['huishou_aid'] = null;
        $this->startTrans();
        try{
            $this->where('id',$id)->update($data);
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->rollback();
            return false;
        }
    }


    //统计
    public function search($param)
    {

        $admin_id = $GLOBALS['userInfo']['id'];
        $value1 = $param['params']['value1'];
        $value2 = $param['params']['value2'];

        # 时间处理
        if (!$value1 && !$value2) {
            $date_today = date('Y-m-d', time());
            $time1 = $date_today . ' 00::00::00';
            $time2 = $date_today . ' 23::59::59';
        } elseif ($value1 && !$value2) {
            $time = time() + 24 * 60 * 60;
            $time1 = date('Y-m-d H:i:s', strtotime($value1));
            $time2 = date('Y-m-d H:i:s', $time);
        } elseif (!$value1 && $value2) {
            $time = date('Y-m-d', strtotime($value2));
            $time1 = $time . ' 00::00::00';
            $time2 = $time . ' 23::59::59';

        } elseif ($value1 && $value2) {
            $time1 = date('Y-m-d H:i:s', strtotime($value1));
            $time2 = date('Y-m-d H:i:s', strtotime($value2));
        }

        $date = array('BETWEEN', [$time1, $time2]);          //时间段 between

        switch ($param['params']['type']) {
            case '1':
                // 认领
                $where_rl['first_claim_date'] = $date;
                $where_rl['check_aid'] = $admin_id;

                // 通过
                $where_tg['check_time'] = $date;
                $where_tg['status'] = array('in', '1,2,3,4,5,7,9,10,11,12');
                $where_tg['check_aid'] = $admin_id;
                // 驳回
                $where_bh['check_time'] = $date;
                $where_bh['status'] = 6;
                $where_bh['check_aid'] = $admin_id;

                // 放款
                $where_fk['fk_time'] = $date;
                $where_fk['status'] = array('in', '3,4,5,12');
                $where_fk['check_aid'] = $admin_id;
                // 回款
                $where_hk['hk_time'] = $date;
                $where_hk['status'] = 5;
                $where_hk['check_aid'] = $admin_id;
                // 移交
                $where_yj['check_time'] = $date;
                $where_yj['transfer'] = 1;
                $where_yj['check_aid'] = $admin_id;
                break;
            case '2':
                // 认领
                $where_rl['second_claim_date'] = $date;
                $where_rl['check2_aid'] = $admin_id;

                // 通过
                $where_tg['check2_time'] = $date;
                $where_tg['status'] = array('in', '2,3,4,5,9,10,11,12');
                $where_tg['check2_aid'] = $admin_id;
                // 驳回
                $where_bh['check2_time'] = $date;
                $where_bh['status'] = 7;
                $where_bh['check2_aid'] = $admin_id;
                // 放款
                $where_fk['fk_time'] = $date;
                $where_fk['status'] = array('in', '3,4,5,12');
                $where_fk['check2_aid'] = $admin_id;
                // 回款
                $where_hk['hk_time'] = $date;
                $where_hk['status'] = 5;
                $where_hk['check2_aid'] = $admin_id;
                // 移交
                $where_yj['check2_time'] = $date;
                $where_yj['transfer'] = 1;
                $where_yj['check2_aid'] = $admin_id;
                break;
            case '3':
                //是否admin查看
                if($admin_id != 1)
                {
                    $where_rl['merchandiser']   = $admin_id;
                    $where_tg['merchandiser']   = $admin_id;
                    $where_hk['merchandiser']   = $admin_id;
                    $where_bh['merchandiser']   = $admin_id;
                    $where_fk['merchandiser']   = $admin_id;
                    $where_yj['merchandiser']   = $admin_id;
                    $where_yq['merchandiser']   = $admin_id;
                    $where_wdq['merchandiser']  = $admin_id;
                }

                // 认领
                $where_rl['third_claim_date'] = $date;

                // 通过
                $where_tg['monepassdate'] = $date;
                $where_tg['status'] = array('in', '3,4,5,9,11,12');
                // 驳回
                $where_bh['monepassdate'] = $date;
                $where_bh['status'] = 10;
                // 放款
                $where_fk['fk_time'] = $date;
                $where_fk['status'] = array('in', '3,4,5,12');
                // 回款
                $where_hk['hk_time'] = $date;
                $where_hk['status'] = 5;
                // 移交
                $where_yj['m1_yijiao_date'] = $date;
                $where_yj['transfer'] = 1;
                //延期
                $where_yq['monepassdate'] = $date;
                $where_yq['status']       = 12;
                //未到期
                $where_wdq['fk_time'] = $date;
                $where_wdq['status'] = array('in', '3,12');
                break;
            case '4':
                // 认领
                $where_rl['third_claim_date'] = $date;
                $where_rl['treasurer'] = $admin_id;
                $where_rl['status'] = array('in', '9,3,4,5,11,12');

                // 通过/放款
                $where_tg['fk_time'] = $date;
                $where_tg['treasurer'] = $admin_id;
                $where_tg['status'] = array('in', '3,4,5,12');

                // 驳回
                $where_bh['lendmoneydate'] = $date;
                $where_bh['treasurer'] = $admin_id;
                $where_bh['status'] = 11;

                // 回款
                $where_hk['hk_time'] = $date;
                $where_hk['treasurer'] = $admin_id;
                $where_hk['status'] = 5;
                break;
            case '5':
                // 认领
                $where_rl['fives_claim_date'] = $date;
                $where_rl['merchandiser2'] = $admin_id;

                // 通过


                // 回款
                $where_hk['hk_time'] = $date;
                $where_hk['status'] = 5;
                $where_hk['merchandiser2'] = $admin_id;
                break;
            default:

                break;
        }


        # 认领数
        $rl = $this->where($where_rl)->count();

        # 通过数
        $tg = $this->where($where_tg)->count();

        # 驳回数
        $bh = $this->where($where_bh)->count();

        # 放款数
        $fk = $this->where($where_fk)->count();

        # 回款数
        $hk = $this->where($where_hk)->count();

        # 移交数
        $yj = $this->where($where_yj)->count();

        #延期数
        $yq = $this->where($where_yq)->count();
        
        #未到期数
        $wdq = $this->where($where_wdq)->count();
        // echo $this->getlastsql();

        # 通过率
        $count_tg = $tg + $bh;

        if ($count_tg == 0) {
            $pass_rate = 0;
        } else {
            $pass_rate = substr(($tg / $count_tg) * 100, 0, 5);

        }

        # 回款率
        if ($param['params']['type'] == 4) {
            if ($tg == 0) {
                $hk_rate = 0;
            } else {
                $hk_rate = substr(($hk / $tg) * 100, 0, 5);
            }
        } else {
            if ($fk == 0) {
                $hk_rate = 0;
            } else {
                $hk_rate = substr(($hk / $fk) * 100, 0, 5);
            }
        }

        # 放款率
        if ($tg == 0) {
            $fk_rate = 0;
        } else {
            $fk_rate = substr(($fk / $tg) * 100, 0, 5);
        }

        $data['rl'] = $rl;
        $data['tg'] = $tg;
        $data['bh'] = $bh;
        $data['fk'] = $fk;
        $data['hk'] = $hk;
        $data['yj'] = $yj;
        $data['yq'] = $yq;
        $data['wdq'] = $wdq;
        $data['pass_rate'] = $pass_rate;
        $data['hk_rate'] = $hk_rate;
        $data['fk_rate'] = $fk_rate;

        return $data;

    }

    /**
     * [createData M1回访通过]
     * @湛慧平
     * @DateTime  2017-08-16T21:19:06+0800
     * @param     array $param [description]
     * @return    [array]                         [description]
     */
    public function createData($param)
    {
        $uid = $param['uid'];
        $discount = $param['discount'];
        $order_number = $param['order_number'];
        $id = $param['id'];
        $map['order_number'] = $order_number;
        $fives_claim_date = date('Y-m-d H:i:s', time());
        $monepassdate = date('Y-m-d H:i:s', time());
        $admin_uid = $GLOBALS['userInfo']['id'];
        $data = [
            'status' => 9,
            'return_visit' => $discount,
            'monepassdate' => $monepassdate,
            'fives_claim_date' => $fives_claim_date,
            'meets3' => json_encode($param['multipleSelection']),
        ];
        $admin_data = ['status' => 1, 'uid' => $uid, 'date' => $monepassdate,
            'admin_user_id' => $admin_uid, 'apply_id' => $id,
            'authstatus' => 4];
        $where = ['auth_admin' => 3];
        $nowdate = date('Y-m-d', time());
        $where['nowdate'] = ['like', '%' . $nowdate . '%'];
        $loanclaim = Db::name('claim_seq')->where($where)->count();
        $loanseq = ['uid' => $uid, 'admin_id' => 0, 'apply_id' => $id, 'seq' => $loanclaim + 1, 'nowdate' => $nowdate, 'auth_admin' => 3];
        $this->startTrans();
        try {
            Db::name('claim_seq')->insert($loanseq);
            Db::name('admin_user_clien')->insert($admin_data);
            $this->save($data, $map);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * [xcreateData M1回访驳回]
     * @湛慧平
     * @DateTime  2017-02-10T21:19:06+0800
     * @param     array $param [description]
     * @return    [array]                         [description]
     */
    public function xcreateData($param)
    {
        $uid = $param['uid'];
        $discount = $param['discount'];
        $order_number = $param['order_number'];
        $id = $param['id'];
        $give_up = $param['status'];
        $map['order_number'] = $order_number;
        $monepassdate = date('Y-m-d H:i:s', time());
        $admin_uid = $GLOBALS['userInfo']['id'];
        //放款订单不可驳回
        $re =$this->checkOrder($order_number);
        if(!$re)
        {
            $this->error = $this->getError();
            return false;
        }
        $data = [
            'status' => 10,
            'return_visit' => $discount,
            'monepassdate' => $monepassdate,
            'meets3' => json_encode($param['multipleSelection']),
            'is_give_up' => $give_up,
        ];

        $admin_data = ['status' => 0, 'uid' => $uid, 'date' => $monepassdate,
            'admin_user_id' => $admin_uid, 'apply_id' => $id,
            'authstatus' => 4];
        Db::name('admin_user_clien')->insert($admin_data);
        $info = $this->save($data, $map);
        if (!$info) {
            return $info;
            exit;
        }
        return $info;

    }
    /**
     * [checkOrder 检测订单 放款不给驳回]
     * @param  string $order_number [description]
     * @return [type]               [description]
     */
    public function checkOrder($order_number = '')
    {
        if(!$order_number)
        {
            $this->error = '订单不存在';
            return false;
        }
        $re = $this->where(['order_number' => $order_number])->field('fk_time')->find();
        if(!$re)
        {
            $this->error = '订单不存在';
            return false;
        }
        if($re['fk_time'])
        {
            $this->error = '订单无法驳回';
            return false;   
        }
        return true;
    }
    /**
     * 用户借款单详情
     * @param  [type] $id   [description]
     * @param  [type] $type [还款方式  1：全额 2：延期]
     * @return [type]       [description]
     */
    public function apply_detials($id, $type = 1)
    {
        $applyModel = new Apply;
        $apply = $applyModel->where('id', $id)->find();
        if ($type == '1') { //全额还款
            $details = $applyModel->loanMoney($apply);
        } else {  //延期
            $details = $applyModel->delayMoney($apply);
        }
        return $details;
    }

    /**
     * 写入催收提示语
     * @return [type] [description]
     */
    public function cuishouTips($param)
    {
        $map['id'] = $param['id'];
        $data['cuishou_tips'] = $param['cuishou_tips'];

        $add = $this->save($data, $map);
        if (false !== $add) {
            return true;
        }
        $this->error = "失败";
        return false;
    }


}